import Cookies from 'js-cookie'
import config from '../config'


/**
 * token 存取操作
 * @type {string}
 */
export const TOKEN_KEY = 'token';
export const TOKEN_TYPE = 'tokenType';

export const setToken = (data) => {
    Cookies.set(TOKEN_KEY, data.token, {
        expires: data.expires_in
    })
};

export const setTokenType = (data) => {
    Cookies.set(TOKEN_TYPE, data.token_type, {
        expires: data.expires_in
    })
};

export const getToken = () => {
    const token = Cookies.get(TOKEN_KEY);
    if (token) return token;
    else return ''
};
export const getTokenType = () => {
    const token_type = Cookies.get(TOKEN_TYPE);
    if (token_type) return token_type;
    else return 'Bearer'
};

export const SET_SESSION = (key, data) => {
    return sessionStorage.setItem(key, JSON.stringify(data))
};

export const GET_SESSION = (key) => {
    return JSON.parse(sessionStorage.getItem(key))
};
export const setMenucode = (data) => {
    return localStorage.setItem('oa-original-menucode', data)
};
export const getMenucode = () => {
    let menucode = localStorage.getItem('oa-original-menucode')
    if (menucode) return menucode;
    else return ''
};
/**
 * 转码 \u
 * @param {} s 
 */
export const decode = (s) => {
    return unescape(s.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1'));
}

/**
 * 根据键名排序
 * @param {} key
 * let arr = [{sort:2},{sort:0}]
 * arr.sort(compare('sort'))
 */
export const compare = (key) => {
    return function (a, b) {
        var value1 = a[key];
        var value2 = b[key];
        return value1 - value2;
    }
}
/**
 * 获取数据类型
 * @param {All} [o] 需要检测的数据
 * @returns {String}
 */
export function getType(o) {
    return Object.prototype.toString.call(o).slice(8, -1);
}
/**
 * 判断是否是指定数据类型
 * @param {All} [o] 需要检测的数据
 * @param {String} [type] 数据类型
 * @returns {Boolean}
 */
export function isKeyType(o, type) {
    return getType(o).toLowerCase() === type.toLowerCase();
}

/**
 * 深拷贝，支持常见类型 object Date Array等引用类型
 * @param {Any} sth
 * @return {Any}
 */
export function deepClone(sth) {
    let copy;
    if (null == sth || "object" != typeof sth) return sth;
    if (isKeyType(sth, 'date')) {
        copy = new Date();
        copy.setTime(sth.getTime());
        return copy;
    }
    if (isKeyType(sth, 'array')) {
        copy = [];
        for (let i = 0, len = sth.length; i < len; i++) {
            copy[i] = deepClone(sth[i]);
        }
        return copy;
    }
    if (isKeyType(sth, 'object')) {
        copy = {};
        for (let attr in sth) {
            if (sth.hasOwnProperty(attr)) copy[attr] = deepClone(sth[attr]);
        }
        return copy;
    }
    return null;
}

/**
 * @desc 函数防抖
 * @param func 目标函数
 * @param wait 延迟执行毫秒数
 * @param immediate true - 立即执行， false - 延迟执行
 */
export function debounce(func, wait = 3000, immediate = true) {
    let timer;
    return function () {
        let context = this,
            args = arguments;
        if (timer) clearTimeout(timer);
        if (immediate) {
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait);
            if (callNow) func.apply(context, args);
        } else {
            timer = setTimeout(() => {
                func.apply
            }, wait)
        }
    }
}
/**
 * js本地分页方法
 * @author Ling
 * @param page 页数
 * @param pageSize 每页数量
 * @param totalData 数据
 * @returns {*[]}
 */
export function getLocalTableData(page = 1, pageSize = 10, totalData = []) {
    const length = totalData.length

    // pageSize大于等于总数据长度，说明只有1页数据或没有数据
    if (pageSize >= length) {
        return totalData
    }
    // pageSize小于总数据长度，数据多余1页
    const num = pageSize * (page - 1) // 计算当前页（不含）之前的所有数据总条数

    if (num < length) { // 如果当前页之前所有数据总条数小于（不能等于）总的数据集长度，则说明当前页码没有超出最大页码
        const startIndex = num // 当前页第一条数据在总数据集中的索引

        const endIndex = num + pageSize - 1 // 当前页最后一条数据索引

        return totalData.filter((_, index) => index >= startIndex && index <= endIndex) // 当前页数据条数小于每页最大条数时，也按最大条数范围筛取数据
    }

    // 当前页码超出最大页码，则计算实际最后一页的page，自动返回最后一页数据
    const size = parseInt(String(length / pageSize)) // 取商

    const rest = length % pageSize // 取余数

    if (rest > 0) { // 余数大于0，说明实际最后一页数据不足pageSize，应该取size+1为最后一条的页码
        return totalData.filter((_, index) => index >= (pageSize * size) && index <= length)
    }
    // 余数等于0，最后一页数据条数正好是pageSize
    // 注：余数不可能小于0
    return totalData.filter((_, index) => index >= (pageSize * (size - 1)) && index <= length)
}
export function listToObj(list, key, value) {
    let obj = {}
    list.forEach(item => {
        obj[item[key]] = item[value]
    })
    return obj
}
export function findPnodeId(data, ID) {
    //设置结果
    let result;
    if (!data) {
        return; //如果data传空，直接返回
    }
    for (var i = 0; i < data.Children.length; i++) {
        let item = data.Children[i];
        if (item.ID == ID) {
            result = data.ID;
            //找到id相等的则返回父id
            return result;
        } else if (item.Children && item.Children.length > 0) {
            //如果有子集，则把子集作为参数重新执行本方法
            result = findPnodeId(item, ID);
            //关键，千万不要直接return本方法，不然即使没有返回值也会将返回return，导致最外层循环中断，直接返回undefined,要有返回值才return才对
            if (result) {
                return result;
            }
        }
    }
    //如果执行循环中都没有return，则在此return
    return result;

}
export function timeSlot(time) {
    let timeNow = new Date();
    let hours = timeNow.getHours();
    let state = ``;
    if (hours >= 0 && hours <= 10) {
        state = `早上好！`;
    } else if (hours >= 10 && hours < 14) {
        state = `中午好！`;
    } else if (hours >= 14 && hours < 18) {
        state = `下午好！`;
    } else if (hours >= 18 && hours <= 24) {
        state = `晚上好！`;
    }
    return state;
}
//格式化时间
export function beautifyTime(dateTimeStamp) {
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
        return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    var result = ''
    if (monthC >= 1) {
        result = "" + parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
        result = "" + parseInt(minC) + "分钟前";
    } else
        result = "刚刚";
    return result;
}
export function formatDayHour(hour) {
    let _hour = Number(hour)
    let day = parseInt(_hour / 24)
    if (_hour < 24) {
        return `${hour}小时`
    } else if (_hour % 24 === 0) {
        return `${day}天`
    } else {
        return `${day}天${_hour - day*24}小时`
    }
}
export function arrayIsRepeat(arr) {
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i]]) {
            return true;
        }
        hash[arr[i]] = true;
    }
    return false;
}


/**
 * 数组排序
 * @param data 数组
 * @param type 排序规则
 */
export function ArrSort(data, type = 'asc') {
    if (data) {
        if (type == 'asc') {
            data.sort(function (a, b) {
                return a < b ? 1 : -1
            })
        } else {
            data.sort(function (a, b) {
                return a > b ? 1 : -1
            })
        }
        return data
    }
}
/**
 * 数组对象排序
 * @param data 数据
 * @param key 排序的键值 true 降序 false 升序
 */
export function ArrayObjectsSort(key, type) {
    return function (obj1, obj2) {
        var a = obj1[key];
        var b = obj2[key];
        if (!isNaN(Number(a)) && !isNaN(Number(b))) {
            a = Number(a);
            b = Number(b);
        }
        if (type == true) {
            return a < b ? 1 : -1
        } else {
            return a > b ? 1 : -1
        }
    }
}
/**
 * 数组去重
 * @param arr 数组
 */
export function ArrayRemoval(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array = [];
    for (var i = 0; i < arr.length; i++) {
        if (!array.includes(arr[i])) {
            array.push(arr[i]);
        }
    }
    return array
}
/**
 * 数组对象去重
 * @param data 数据
 * @param key 去重的键值
 */
export function ArrayObjectsRemoval(data, key) {
    if (data && key) {
        var result = [];
        var obj = {};
        for (var i = 0; i < data.length; i++) {
            if (!obj[data[i][key]]) {
                result.push(data[i]);
                obj[data[i][key]] = true;
            }
        }
        return result
    } else {
        console.error('请检查参数出入是否正确！')
    }

}
export function getArrayObjAdd(data, objName) {
    let sum = data.reduce((r, d) => r + Number(d[objName]), 0)
    return sum
}
export function percentage(num, total) {
    if (total && num <= total) {
        return ((num / total) * 100).toFixed(2) + '%'
    } else if (total == 0 || num > total) {
        return '0%'
    }
}
export function getTimeDateNow() {
    var now = new Date();

    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日

    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    if (hh < 10)
        clock += "0";
    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm;
    return (clock);
}